package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.dto.role.UserRoleDto;
import com.battle.pojo.entity.*;
import com.battle.pojo.enums.PersonMpWarCaseTypeEnum;
import com.battle.pojo.param.carWarCase.*;
import com.battle.pojo.vo.carWarCase.*;
import com.battle.pojo.dto.carWarCase.*;
import com.battle.pojo.vo.personMpWarCase.GetPersonMpWarCaseDownListVo;
import com.battle.pojo.vo.skillCertificate.GetSkillCertificateListVo;
import com.battle.pojo.vo.user.GetUserListVo;
import com.battle.service.repository.in.*;
import com.battle.service.service.in.CarWarCaseService;
import com.battle.service.utils.ExcelUtils;
import com.battle.service.utils.StringPassUtil;
import jakarta.servlet.http.HttpServletResponse;
import nirvana.core.context.WebContext;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：车辆战力表服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class CarWarCaseServiceImpl implements CarWarCaseService {

    private final CarWarCaseRepository carWarCaseRepository;
    private final OrganizationRepository organizationRepository;
    private final PersonMpWarCaseRepository personMpWarCaseRepository;
    private final PersonWarCaseRepository personWarCaseRepository;
    private final UserRepository userRepository;

    public CarWarCaseServiceImpl(CarWarCaseRepository carWarCaseRepository, OrganizationRepository organizationRepository, PersonMpWarCaseRepository personMpWarCaseRepository, PersonWarCaseRepository personWarCaseRepository, UserRepository userRepository) {
        this.carWarCaseRepository = carWarCaseRepository;
        this.organizationRepository = organizationRepository;
        this.personMpWarCaseRepository = personMpWarCaseRepository;
        this.personWarCaseRepository = personWarCaseRepository;
        this.userRepository = userRepository;
    }


    /**
     * 创建车辆战力表
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createCarWarCase(CreateCarWarCaseParam param) {
        //判断技能名称+技能类型是否重复
        List<CarWarCase> skillCertificates = carWarCaseRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<CarWarCase>()
                        .eq(CarWarCase::getCode, param.getCode())
                        .eq(CarWarCase::getIsDelete, 0)
        );
        if (CollectionUtil.isNotEmpty(skillCertificates)) {
            throw new BizException("车牌号不能重复");
        }

        CarWarCase carWarCase = new CarWarCase();
        BeanUtils.copyProperties(param, carWarCase);
        Long id = IdGenerator.SNOW.generate();
        carWarCase.setId(id);
        //随机生成60-100之间的数字
        carWarCase.setCombatPower((int) (Math.random() * 40 + 60));
        // TODO 设置用户名称
//        carWarCase.setCreatorName(WebContext.getCurrentUserId());

        //根据当前组织架构id拿到所有的层级架构
        String path = organizationRepository.selectPathById(param.getOrganizationId(), null);
        carWarCase.setPath(path);

        //批量添加人员战力mp表
        personMpWarCaseRepository.bathAddPersonMpWarCase(PersonMpWarCaseTypeEnum.car, id, param.getPersonIds());

        carWarCaseRepository.create(carWarCase);
    }

    /**
     * 修改车辆战力表
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editCarWarCase(EditCarWarCaseParam param) {
        Long id = param.getId();
        CarWarCase carWarCase = carWarCaseRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, carWarCase);

        //根据当前组织架构id拿到所有的层级架构
        String path = organizationRepository.selectPathById(param.getOrganizationId(), null);
        carWarCase.setPath(path);

        //批量移除人员mp表然后添加人员战力mp表
        personMpWarCaseRepository.removeByFidAndType(id, PersonMpWarCaseTypeEnum.car);
        personMpWarCaseRepository.bathAddPersonMpWarCase(PersonMpWarCaseTypeEnum.car, id, param.getPersonIds());

        carWarCaseRepository.edit(carWarCase);
    }

    /**
     * 移除车辆战力表
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCarWarCase(Long id) {
        carWarCaseRepository.removeById(id);
        personMpWarCaseRepository.removeByFidAndType(id, PersonMpWarCaseTypeEnum.car);
    }



    /**
     * 获取车辆战力表详情
     *
     * @param id
     * @return
     */
    @Override
    public GetCarWarCaseVo getCarWarCase(Long id) {
        CarWarCase carWarCase = carWarCaseRepository.getByIdCheck(id);
        GetCarWarCaseVo vo = new GetCarWarCaseVo();
        BeanUtils.copyProperties(carWarCase, vo);

        List<PersonMpWarCase> byFidAndType = personMpWarCaseRepository.getByFidAndType(id, PersonMpWarCaseTypeEnum.car);
        if (CollectionUtil.isNotEmpty(byFidAndType)){
            List<Long> personIds = new ArrayList<>();
            for (PersonMpWarCase personMpWarCase : byFidAndType) {
                personIds.add(personMpWarCase.getPersonId());
            }
            vo.setPersonIds(personIds);
            //根据personIds批量查询
            List<PersonWarCase> personWarCases = personWarCaseRepository.listByIds(personIds);
            if (CollectionUtil.isNotEmpty(personWarCases)){
                //stream流提取personWarCases的name，用逗号分隔
                String personNames = personWarCases.stream()
                        .map(PersonWarCase::getName)
                        .collect(Collectors.joining(","));
                vo.setPersonNames(personNames);
            }
        }

        return vo;
    }

    /**
     * 获取车辆战力表 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetCarWarCaseListVo> getCarWarCaseList(GetCarWarCaseListParam param) {

        SelectCarWarCaseDto dto = new SelectCarWarCaseDto();
        BeanUtils.copyProperties(param, dto);
        if (param.getOrderBy()!=null){
            dto.setOrderBy(StringPassUtil.convertToSnakeCase(param.getOrderBy()));
        }
        Page<CarWarCase> page = carWarCaseRepository.selectCarWarCase(dto);
        List<CarWarCase> carWarCaseList = page.getRecords();

        List<GetCarWarCaseListVo> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(carWarCaseList)){
            List<Long> ids = carWarCaseList.stream().map(CarWarCase::getId).toList();
            //创建人
            List<Long> userIds = carWarCaseList.stream().map(CarWarCase::getCreator).toList();
            Map<Long, User> userMap = userRepository.getMap(userIds);

            Map<Long, List<GetPersonMpWarCaseDownListVo>> listMap = personMpWarCaseRepository.getDtoByFids(ids);


            for (CarWarCase carWarCase : carWarCaseList) {
                GetCarWarCaseListVo vo = new GetCarWarCaseListVo();
                BeanUtils.copyProperties(carWarCase, vo);

                Long id = vo.getId();
                List<GetPersonMpWarCaseDownListVo> roleDtoList = listMap.get(id);
                if (roleDtoList != null) {
                    String personNames = roleDtoList.stream()
                            .map(GetPersonMpWarCaseDownListVo::getPersonName)
                            .collect(Collectors.joining(","));
                    vo.setPersonNames(personNames);
                }

                Organization byId = organizationRepository.getById(vo.getOrganizationId());
                if (byId != null) {
                    vo.setOrganizationName(byId.getName());
                }

                User user = userMap.get(carWarCase.getCreator());
                if (user != null) {
                    vo.setCreatorName(user.getName());
                }
                vo.setCreateTime(carWarCase.getCreateTime());
                list.add(vo);
            }
        }
        return new PageResult<>(list, page);

    }

    /**
     * 导出车辆战力
     * @param param
     * @param response
     * @throws IOException
     */
    @Override
    public void export(GetCarWarCaseListParam param, HttpServletResponse response) throws IOException {
        param.setSize(Long.MAX_VALUE);
        PageResult<GetCarWarCaseListVo> pageResult = getCarWarCaseList(param);
        List<GetCarWarCaseListVo> list = pageResult.getRecords();
        ExcelUtils.exportExcel(list, "车辆战力", "车辆战力", GetCarWarCaseListVo.class, "车辆战力",response);
    }

    /**
     * 获取车辆战力表下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetCarWarCaseDownListVo> getCarWarCaseDownList(GetCarWarCaseDownListParam param) {
        CarWarCase po = new CarWarCase();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<CarWarCase> carWarCaseList = carWarCaseRepository.getListByEntity(po);

        List<GetCarWarCaseDownListVo> list = new ArrayList<>();
        for (CarWarCase carWarCase : carWarCaseList) {
            GetCarWarCaseDownListVo vo = new GetCarWarCaseDownListVo();
            BeanUtils.copyProperties(carWarCase, vo);
            list.add(vo);
        }
        return list;
    }


}



